﻿using Blm.PgsqlDriver.Helpers;
using Blm.Utils.Utility;
using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using VisionCloud.Utility;

namespace VisionCloud.Web.Service
{
    /// <summary>
    /// 解压计算服务上传的日志
    /// </summary>
    public class UnzipComputeData : BackgroundService
    {
        /// <summary>
        /// 报告文件存储路径
        /// </summary>
        private static readonly string taskReportData = ConfigHelper.GetValue<string>("TaskReportData");
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    Dowork();
                }
                catch
                {
                    // 注：定时服务不记录日志
                }
                finally
                {
                    await Task.Delay(100);
                }

            }
        }

        /// <summary>
        /// 工作内容
        /// </summary>
        private static void Dowork()
        {
            string zipDir = Path.Combine(taskReportData, "compute_task/zip");

            if (Directory.Exists(zipDir))
            {
                var files = Directory.GetFiles(zipDir);
                foreach (string file in files)
                {
                    string fileName = Path.GetFileNameWithoutExtension(file);
                    var arr = fileName.Split('_', StringSplitOptions.RemoveEmptyEntries);
                    if (arr.Length == 2)
                    {
                        try
                        {
                            string taskId = arr[1];
                            string cloudComputeTaskDir = Path.Combine(taskReportData, "compute_task", taskId);
                            string extractMessage = FileInfoUtil.ExtractToDirectory(file, cloudComputeTaskDir, true);
                            if (!string.IsNullOrWhiteSpace(extractMessage))
                            {
                                string errorFolder = Path.Combine(taskReportData, "error");
                                if (!Directory.Exists(errorFolder))
                                {
                                    Directory.CreateDirectory(errorFolder);
                                }
                                var zipFile = new FileInfo(file);
                                // 将解压出错文件移动到erro文件夹中
                                string errorPath = Path.Combine(errorFolder, zipFile.Name);
                                // 错误文件已存在将其删除
                                FileInfoUtil.DeleteFile(errorPath);
                                File.Move(file, errorPath);
                            }
                            string sql = $"update \"CSMSTask\" set \"LastUpdatedDate\"='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}',\"ReportUploadDateTime\"='{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}',\"IsNew\"=TRUE,\"ResultDataFilePath\"='{cloudComputeTaskDir}' where \"TaskId\" ='{taskId}'";
                            PgSqlHelper.ExecuteNonQuery(System.Data.CommandType.Text, sql);
                            File.Delete(file);
                        }
                        catch (Exception ex)
                        {
                            Logger.Info("处理计算数据发生错误", ex);
                        }
                    }
                }
            }
        }
    }
}
